﻿using System.Collections;
using umbraco.cms.businesslogic.member;

namespace Designit.Umb.Newsletter.Bll
{
    public class ConfirmUnsubscribe
    {
        public static Member Confirm(string guid)
        {
            var memberid =
                umbraco.BusinessLogic.Application.SqlHelper.ExecuteScalar<int>("select top 1 memberId from newsLetterUnsubscribeMember where guid=@guid",
                                                                               umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@guid", guid));
            var mail =
                umbraco.BusinessLogic.Application.SqlHelper.ExecuteScalar<string>("select top 1 Email from cmsMember where nodeId=@memberid",
                                                                                  umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@memberid", memberid));
            Member member = Member.GetMemberFromEmail(mail);
            using (var reader =
                umbraco.BusinessLogic.Application.SqlHelper.ExecuteReader("select * from newsLetterUnsubscribeMember where guid=@guid",
                                                                          umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@guid", guid)))
            {
                while (reader.Read())
                {
                    member.RemoveGroup(reader.GetInt("groupId"));
                }
            }
            //RemoveFromActiveCampaign(memberid);
            umbraco.BusinessLogic.Application.SqlHelper.ExecuteNonQuery("delete from newsLetterUnsubscribeMember where guid=@guid",
                                                                        umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@guid", guid));
            return member;
        }
    }
}
